const Model = require('sqltool/src/model')
const utils = require('../utils')

class UserModel extends Model {
  createPassword (password, salt) {
    return utils.md5(salt + password + salt)
  }

  async createUser (data) {
    const salt = utils.randomToken(128)
    const password = this.createPassword(data.password, salt)

    const { insertId } = await this.create({
      ...data,
      password: password,
      salt: salt
    })

    return insertId
  }

  async validUser (username, password) {
    const where = {
      $or: {
        username: username,
        email: username
      }
    }

    const user = await this.findOne({
      attrs: ['id', 'salt', 'password', 'status'],
      where: where
    })

    if (!user) return { valid: false, msg: '用户不存在' }

    if (user.status !== 1) return { valid: false, msg: '用户已经被禁用' }

    if (this.createPassword(password, user.salt) !== user.password) {
      return { valid: false, msg: '密码不匹配' }
    }

    return { valid: true, msg: 'ok', id: user.id }
  }

  getUserInfo (userId) {
    return this.findOne({
      attrs: ['id', 'username', 'nickname', 'avatar', 'email', 'sign', 'type', 'createdAt', 'updatedAt'],
      where: { id: userId }
    })
  }

  async addOauthUser (oauthType, data) {
    const unionid = data.unionid

    const user = await this.findOne({
      attrs: ['id'],
      where: {
        unionid: unionid,
        oauthType: oauthType
      }
    })

    if (user) {
      // await this.update({
      //   avatar: data.avatar
      // }, { id: user.id })

      return user.id
    }

    const { insertId } = await this.create({
      unionid: data.unionid,
      nickname: data.nickname,
      email: data.email,
      avatar: data.avatar,
      oauthType: oauthType
    })

    return insertId
  }
}

module.exports = UserModel
